package com.nus.servlets;

import com.nus.beans.Project;
import com.nus.beans.User;
import com.nus.database.ProjectsDBManager;
import com.nus.services.ConversionService;
import com.nus.services.ValidationService;
import org.apache.log4j.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/25/12
 * Time: 11:54 PM
 * To change this template use File | Settings | File Templates.
 */
public class CreateProjectServlet extends AbstractServlet {
    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {        String projectName = request.getParameter("projectName");
        String startYear = request.getParameter("startYear");
        String startMonth = request.getParameter("startMonth");
        String startDate = request.getParameter("startDate");
        String endYear = request.getParameter("endYear");
        String endMonth = request.getParameter("endMonth");
        String endDate = request.getParameter("endDate");
        String deadlineYear = request.getParameter("deadlineYear");
        String deadlineMonth = request.getParameter("deadlineMonth");
        String deadlineDate = request.getParameter("deadlineDate");

        List<User> assignUsers = new ArrayList<User>();
        Enumeration e = request.getParameterNames();
        String tmpUserId;
        User user;
        int userId;
        while (e.hasMoreElements()) {
            String parameter = String.valueOf(e.nextElement());
            if (parameter.startsWith("user_")) {
                tmpUserId = parameter.substring(parameter.indexOf("_") + 1);
                userId = Integer.parseInt(tmpUserId);
                user = new User();
                user.setUserId(userId);
                assignUsers.add(user);
            }
        }

        ValidationService validationService = new ValidationService();
        String errorMessage;

        String nextPage = "LoadcreateProjects.do";
        RequestDispatcher requestDispatcher = request.getRequestDispatcher(nextPage);

        if (validationService.isEmpty(projectName)) {
            errorMessage = "Project name should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(startYear) || validationService.isEmpty(startMonth) || validationService.isEmpty(startDate)) {
            errorMessage = "Start date should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(endYear) || validationService.isEmpty(endMonth) || validationService.isEmpty(endDate)) {
            errorMessage = "Estimated end date should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(deadlineYear) || validationService.isEmpty(deadlineMonth) || validationService.isEmpty(deadlineDate)) {
            errorMessage = "Deadline should not be empty.";
            logger.error(errorMessage);
        } else {
            ConversionService conversionService = new ConversionService();
            Project project = new Project();
            project.setProjectName(projectName);

            Date startDateActual = conversionService.getDate(startYear, startMonth, startDate);
            Date endDateActual = conversionService.getDate(endYear, endMonth, endDate);
            Date deadlineDateActual = conversionService.getDate(deadlineYear, deadlineMonth, deadlineDate);

            if (startDateActual == null) {
                errorMessage = "Invalid value entered for start date";
            } else if (endDateActual == null) {
                errorMessage = "Invalid value entered for end date";
            } else if (deadlineDateActual == null) {
                errorMessage = "Invalid value entered for deadline date";
            } else if (startDateActual.after(endDateActual)) {
                errorMessage = "Invalid input. End date should be later than start date";
            } else if (startDateActual.after(deadlineDateActual)) {
                errorMessage = "Invalid input. Deadline date should be later than start date";
            } else {
                project.setStartingDate(startDateActual);
                project.setEstimatedEndDate(endDateActual);
                project.setDeadline(deadlineDateActual);

                Connection connection = getUserDatabaseConnection(request);
                ProjectsDBManager projectDBManager = new ProjectsDBManager(connection);
                projectDBManager.createProject(project, assignUsers);
                projectDBManager.close();
                errorMessage = "Project successfully created.";
            }
        }

        request.setAttribute("ERROR_MESSAGE", errorMessage);
        requestDispatcher.forward(request, response);
    }
}